<script setup>
import { ref, reactive,watch } from 'vue'
import { User,Lock } from '@element-plus/icons-vue'
import { loginHandler } from '../api/login.js'
import { CONFIG } from '../config/index.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const loginInfo = reactive({
    username: "",
    password: ""
})
const router = useRouter()
const loginRef = ref()
const rules = reactive({
    username: [
        {required: true, message: "请输入用户名", trigger: 'blur'},
    ],
    password: [
        {required: true, message: "请输入密码", trigger: 'blur'},
    ],
})

let loginButtonDisabled = ref(true)
// 监听username和password输入的情况
watch([() => loginInfo.username, () => loginInfo.password],() => {
    loginRef.value.validate((valid) =>{
        if (valid) {
            loginButtonDisabled.value = false
        } else {
            loginButtonDisabled.value = true
        }
    })
})

// 实现一个登录接口
const submitForm = async () => {
    console.log("loginInfo:",loginInfo)
    loginHandler(loginInfo.username, loginInfo.password).then((response) => {
        console.log("登录response",response)
        if (response.data.status == 200) {
            const token = response.data.data.token //存储token到localstorage下
            window.localStorage.setItem(CONFIG.TOKEN_NAME, token)
            ElMessage({
                message: response.data.message,
                type: "success"
            })
            router.replace("/") //跳转首页
        }
    })
}


</script>

<template>
    <div id="login" style="width: 100vw;">
        <el-card>
            <h2>后台登录系统</h2>
            <el-form
                ref="loginRef"
                :model="loginInfo"
                :rules="rules"
            >
                <el-form-item prop="username" class="form-item">
                <el-input placeholder="请输入用户名" clearable :prefix-icon="User" v-model.number="loginInfo.username"/>
                </el-form-item>

                <el-form-item prop="password" class="form-item">
                <el-input placeholder="请输入密码" :prefix-icon="Lock" show-password v-model="loginInfo.password" type="password" autocomplete="off"/>
                </el-form-item>

                <el-form-item>
                    <el-button style="margin: 10px auto 0 auto;" :disabled="loginButtonDisabled" type="primary" @click="submitForm(ruleFormRef)">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
<style scoped>
.text {
    font-size: 14px;
}

.item {
    padding: 18px 0;
}
.el-card {
    width: 480px;
    margin: 0 auto 300px auto;
}
.form-item {
    width: 240px;
    margin: 0 auto 20px auto;
}

</style>
